import { useContext, useReducer, useRef, useEffect } from 'react';
import { createContext } from 'react';

export const ReactReduxContext = createContext();

export const Provider = ReactReduxContext.Provider;
// export function Provider({ store, children }) {
//     return (
//         <ReactReduxContext.Provider value={store}>
//             {children}
//         </ReactReduxContext.Provider>
//     );
// }

export function useSelector(selector) {
    // 获取 Redux store
    const store = useContext(ReactReduxContext);

    // 强制更新组件的函数
    const [, forceRender] = useReducer(s => s + 1, 0);

    // 保存上一次的选择结果
    const latestSelectedState = useRef();

    // 获取当前 state
    const selectedState = selector(store.getState());

    useEffect(() => {
        // 订阅 store 变化
        const unsubscribe = store.subscribe(() => {
            // 获取最新的选择结果
            const newSelectedState = selector(store.getState());

            // 比较新旧值是否相等
            if (newSelectedState !== latestSelectedState.current) {
                // 不相等则更新组件
                latestSelectedState.current = newSelectedState;
                forceRender();
            }
        });

        // 清理订阅
        return () => unsubscribe();
    }, [store, selector]);

    return selectedState;
}

export function useDispatch() {
    const store = useContext(ReactReduxContext);
    return store.dispatch;
}
